{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "6841ac05",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Validation Accuracy: 0.7318435754189944\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.metrics import accuracy_score\n",
    "\n",
    "# 加载数据集\n",
    "train_data = pd.read_csv('train.csv')\n",
    "test_data = pd.read_csv('test.csv')\n",
    "\n",
    "# 数据探索与预处理\n",
    "# print(train_data.head())\n",
    "# print(train_data.info())\n",
    "\n",
    "# 特征工程\n",
    "def process_data(data):\n",
    "    # 处理缺失值\n",
    "    data['Age'].fillna(data['Age'].median(), inplace=True)\n",
    "    data['Fare'].fillna(data['Fare'].median(), inplace=True)\n",
    "    \n",
    "    data['Cabin'].fillna('',inplace=True)\n",
    "    data['Cabin'] = data['Cabin'].apply(transform_value)\n",
    "    \n",
    "    # 添加新特征：家庭成员数量\n",
    "    data['FamilySize'] = data['SibSp'] + data['Parch'] + 1\n",
    "    \n",
    "    # 编码分类变量\n",
    "    data = pd.get_dummies(data, columns=['Sex', 'Embarked'])\n",
    "    \n",
    "    return data\n",
    "\n",
    "def transform_value(x):\n",
    "    if len(x)>0:\n",
    "        return 1\n",
    "    else:\n",
    "        return 0\n",
    "\n",
    "train_data = process_data(train_data)\n",
    "test_data = process_data(test_data)\n",
    "# print(train_data.head(20))\n",
    "\n",
    "# 选择特征和目标变量\n",
    "features = ['Pclass', 'Age', 'SibSp', 'Parch', 'Fare', 'FamilySize', 'Sex_female',\n",
    "            'Sex_male', 'Embarked_C', 'Embarked_Q', 'Embarked_S']\n",
    "X = train_data[features]\n",
    "y = train_data['Survived']\n",
    "# print(train_data.head())\n",
    "\n",
    "# 划分训练集和验证集\n",
    "X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "# 建立模型\n",
    "model = RandomForestClassifier(random_state=42)\n",
    "\n",
    "# 模型训练\n",
    "model.fit(X_train, y_train)\n",
    "\n",
    "# 模型评估\n",
    "y_pred = model.predict(X_val)\n",
    "accuracy = accuracy_score(y_val, y_pred)\n",
    "print(\"Validation Accuracy:\", accuracy)\n",
    "\n",
    "# 预测测试集\n",
    "X_test = test_data[features]\n",
    "predictions = model.predict(X_test)\n",
    "\n",
    "# 生成提交文件\n",
    "submission = pd.DataFrame({'PassengerId': test_data['PassengerId'], 'Survived': predictions})\n",
    "submission.to_csv('submission.csv', index=False)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
